﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Infrastructure;

namespace Swimj.AspNetCore.Mvc
{
    public class CustomFileResultExecutor : IActionResultExecutor<CustomFileResult>
    {
        public async Task ExecuteAsync(ActionContext context, CustomFileResult result)
        {
            var stream = result.FileStream;
            byte[] bytes = new byte[result.FileStream.Length];
            var _ = await stream.ReadAsync(bytes, 0, bytes.Length);
            //设置当前流的位置为流的开始
            stream.Seek(0, SeekOrigin.Begin);

            context.HttpContext.Response.ContentType = "application/octet-stream";
            context.HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
            context.HttpContext.Response.Headers.Add("Content-Disposition",
                $"attachment; filename={result.FileName}; filename*=UTF-8''{result.FileName}");
            await context.HttpContext.Response.Body.WriteAsync(bytes, 0, bytes.Length);
        }
    }
}